package com.xyh;

import com.xyh.web.context.ApplicationContext;
import com.xyh.web.context.AbstractContextLoaderInitializer;
import com.xyh.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

public class AppStarter extends AbstractContextLoaderInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        super.onStartup(servletContext);
		registerDispatcherServlet(servletContext);
    }

	private void registerDispatcherServlet(ServletContext servletContext) {
		ApplicationContext servletAppContext = createServletApplicationContext();
		DispatcherServlet dispatcherServlet = new DispatcherServlet(servletAppContext);
        ServletRegistration.Dynamic registration = servletContext.addServlet("app", dispatcherServlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/"); //映射路径
	}

	/**
	 * 根据SpringMVC配置类（对应xml版的springMVC.xml）new出来的子容器
	 */
	private ApplicationContext createServletApplicationContext() {
		ApplicationContext applicationContext = new ApplicationContext();
		applicationContext.register("SpringMVCConfig");
		return applicationContext;
	}
}

//public class AppStarter implements WebApplicationInitializer {
//    @Override
//    public void onStartup(ServletContext servletContext) throws ServletException {
//        ApplicationContext context = new ApplicationContext();
//        DispatcherServlet servlet = new DispatcherServlet(context);
//        ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
//        registration.setLoadOnStartup(1);
//        registration.addMapping("/"); //映射路径
//    }
//}
